package com.jyu.work.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jyu.common.context.BaseContext;
import com.jyu.common.result.PageResult;
import com.jyu.pojo.DTO.UserLoginDTO;
import com.jyu.common.Utils.JwtUtil;
import com.jyu.common.result.Result;
import com.jyu.pojo.VO.LoginUserVO;
import com.jyu.common.properties.JwtProperties;
import com.jyu.pojo.VO.UserVO;
import com.jyu.pojo.entity.User;
import com.jyu.work.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
@CrossOrigin(origins = "http://127.0.0.1:5173")
@Api("用户相关接口")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @GetMapping("/hello")
    public Result hello(){
        System.out.println("hello");
        return Result.success(null,"测试成功");
    }


    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result register (@RequestBody User users){
        log.warn("用户注册传入数据:{}", users);
        // 对数据库插入
        userService.register(users);

        return Result.success(null, "注册成功");
    }


    // 处理跨域的方法
    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO loginDTO){
        log.warn("传入的值： {}", loginDTO);
        // 判断是否为空
        if(loginDTO.getPassword() == null || loginDTO.getUsername() == null ){
            return Result.error("账号密码不能为空");
        }

        User loginUser = userService.login(loginDTO);

        // 登陆后绑定 线程上下文id
        BaseContext.setCurrentId(Long.valueOf(loginUser.getId()));


        // 为用户生成 jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("user_id", loginUser.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(),claims);
        LoginUserVO userLoginVO = new LoginUserVO();
        userLoginVO.setId(String.valueOf(loginUser.getId()));
        userLoginVO.setToken(token);

        // 返回令牌
        return Result.success(userLoginVO,"登录成功");
    }


    @GetMapping("/{id}")
    public Result selectById( @PathVariable("id") Integer id) {
        User byId = userService.getById(id);
        return Result.success(byId);
    }


    @GetMapping("/page")
    public Result page(Integer page, Integer pageSize, String name) {
        // 分页对象存放分页信息
        Page<User> pageInfo = new Page(page,pageSize);
        // 新建条件查询器
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.like(name!=null, User::getUserName, name);
        userService.page(pageInfo,qw);
        // 前端展示对象
        // dto 后端接受对象
        List<UserVO> list = new ArrayList<>();
        for(User user: pageInfo.getRecords()){
            UserVO vo = new UserVO();
            BeanUtils.copyProperties(user,vo);
            list.add(vo);
        }

        long total = pageInfo.getTotal();
        // 将查询的总条目数和数据集合给到 PageResult
        return Result.success(new PageResult(total, list));
    }


}
